# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from zc_core.model.items import Box
from zc_core.spiders.base import BaseSpider
from huiemall.rules import *


class OrderSpider(BaseSpider):
    name = 'order'
    # 常用链接
    order_list_url = 'http://www.huiemall.com/EpointMallHeFeiService/rest/system/getgonggaolist'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        settings = get_project_settings()
        for page in range(1, settings.get('MAX_ORDER_PAGE', 30000)):
            yield Request(
                method='POST',
                url=self.order_list_url,
                headers={
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Content-Type': 'application/json',
                },
                body=json.dumps({
                    "keyword": "",
                    "page": str(page),
                    "size": "10",
                    "type": "cj",
                    "url": "http://www.huiemall.com/HeFei/notice.html?type=cj&page={}&keyword=".format(str(page)),
                    "referer": "http://www.huiemall.com/HeFei/notice.html?type=cj&page={}&keyword=".format(str(page))
                }),
                meta={
                    'reqType': 'order',
                    'page': str(page),
                },
                callback=self.parse_order,
                errback=self.error_back,
                priority=100,
            )

    def parse_order(self, response):
        page = response.meta.get('page', 1)
        # 处理订单列表
        order_list = parse_order(response)
        if order_list:
            self.logger.info('列表: page=%s, count=%s' % (page, len(order_list)))
            yield Box('order', self.batch_no, order_list)
        else:
            self.logger.info('无单: page=%s' % page)
